package mapper;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 *自定义ClassLoader
 */
public final class MyClassLoader extends ClassLoader {

  private String classDir;// 文件目录

  @Override
  public Class<?> findClass(String name) {
    String realPath = classDir + name.replace(".", "/") + ".class";//class文件的真实路径
    byte[] cLassBytes = null;
    Path path = null;

    try {

      path = Paths.get(new URI(realPath));
      cLassBytes = Files.readAllBytes(path);

    } catch (IOException | URISyntaxException e) {
      e.printStackTrace();
    }
    Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);//调用父类的defineClass方法
    return clazz;
  }


  public MyClassLoader(String classDir) {
    this.classDir = "file:/".concat(classDir);//拼接 “file:/”前缀
  }
}
